package util

import (
	"bytes"
	"encoding/json"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"io/ioutil"
)

func ToJson(object interface{}) string {
	objectBytes, _ := json.Marshal(object)
	return string(objectBytes)
}

func ToGBK2(s string) string {
	bs := []byte(s)
	text, _ := ToGBK(bs)
	return text
}

func ToGBK(bs []byte) (text string, err error) {
	gbkBytes, err := ToGBKBytes(bs)
	if err != nil {
		return "", err
	}
	return string(gbkBytes), nil
}

func ToGBKBytes(bs []byte) ([]byte, error) {
	utf8Reader := transform.NewReader(bytes.NewReader(bs), simplifiedchinese.GBK.NewDecoder())
	all, err := ioutil.ReadAll(utf8Reader)
	if err != nil {
		return nil, err
	}
	return all, nil
}

func LeftFull(text string, size int) string {
	return LeftFullString(text, size, "0")
}

func LeftFullString(text string, size int, full string) string {
	textLen := len(text)
	fullSize := size - textLen
	if fullSize > 0 {
		for i := 0; i < fullSize; i++ {
			text += full
		}
	}
	return text
}
